package Message;

import Access_Token.AccessToken;
import com.alibaba.fastjson.JSONObject;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

public class SendWechatMessage {
    private final static String MSGTYPE_TEXT = "text";//消息类型
    private final static String TOPARTY="@all";//将消息发送所有成员
    private final static String CORPSECET="i90j61BPbB26I21L6gZylr8FdcoAqTc2ujKUXPuOcbg";//企业密钥
    private final static String CORPID="ww57280925e3a2ccd6";//企业ID
    private final static String ACCCESS_TOKEN_URL="https://qyapi.weixin.qq.com/cgi-bin/gettoken";//访问权限码
    private final static String TOKEN_URL="https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token=";//会话请求
/**
 * 获取AccessToken
 *
 * @return Access_Token.AccessToken
 * @author zhuwanyi
 * @create 2024/12/17
 **/

public static AccessToken getAccessToken(){
        AccessToken token = new AccessToken();
        //访问微信服务器
    String url = ACCCESS_TOKEN_URL+"?corpid="+CORPID+"&corpsecret="+CORPSECET;
    try {
        URL url1 = new URL(url);
        //开启链接
        HttpURLConnection http= (HttpURLConnection) url1.openConnection();
        http.setRequestMethod("GET");
        http.setRequestProperty("Content-Type","application/x-www-form-urlencoded;charset=UTF-8");
        //将URL连接用于输入和输出
        http.setDoOutput(true);
        http.setDoInput(true);
        //进行连接，不返回对象
        http.connect();
        //获得输入内容，将其存储在缓存区
        InputStream inputStream=http.getInputStream();
        int size=inputStream.available();
        byte[] data = new byte[size];
        inputStream.read(data);
        String message = new String(data,"UTF-8");//将字节数组转换为字符串
        JSONObject jsonObject = JSONObject.parseObject(message);//将字符串转换为JSON对象
        //提取内容，放入对象
        token.setAccess_token(jsonObject.getString("access_token"));
        token.setExpires_in(jsonObject.getInteger("expires_in"));
    } catch (MalformedURLException e) {
        throw new RuntimeException(e);
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
    return token;
    }
/**
 * 企业接口向下属关注用户发送给微信消息
 *
 * @param toUser 成员ID列表
 * @param toParty 部门ID列表
 * @param toTag 标签ID列表
 * @param content 消息内容
 * @param safe 是否保密
 * @return void
 * @author zhuwanyi
 * @create 2024/12/17
 **/

@SuppressWarnings("deprecation")
    public void sendWeChatMessage(String toUser, String toParty, String toTag, String content,String safe) {
AccessToken token = getAccessToken();
String url = TOKEN_URL+token.getAccess_token();
    //封装发送消息请求JSON
    StringBuffer stringBuffer = new StringBuffer();
    stringBuffer.append("{");
    stringBuffer.append("\"touser\":" + "\"" + toUser + "\",");
    stringBuffer.append("\"toparty\":" + "\"" + toParty + "\",");
    stringBuffer.append("\"totag\":" + "\"" + toTag + "\",");
    stringBuffer.append("\"msgtype\":" + "\"" + MSGTYPE_TEXT + "\",");
    stringBuffer.append("\"text\":" + "{");
    stringBuffer.append("\"content\":" + "\"" + content + "\"");
    stringBuffer.append("}");
    stringBuffer.append(",\"safe\":" + "\"" + safe + "\",");
    stringBuffer.append("\"agentid\":" + "\"" + "1000007" + "\",");
    stringBuffer.append("\"debug\":" + "\"" + "1" + "\"");
    stringBuffer.append("}");
    String json = stringBuffer.toString();
    System.out.println(json);

    try {
        URL posturl = new URL(url);
        HttpURLConnection http = (HttpURLConnection) posturl.openConnection();
        http.setRequestMethod("POST");
        http.setRequestProperty("Content-Type","application/x-www-form-urlencoded;charset=UTF-8");
        http.setDoOutput(true);
        http.setDoInput(true);
        // 连接超时30秒
        System.setProperty("sun.net.client.defaultConnectTimeout", "30000");
        // 读取超时30秒
        System.setProperty("sun.net.client.defaultReadTimeout", "30000");
        http.connect();
        OutputStream os = http.getOutputStream();
        os.write(json.getBytes("UTF-8"));
        InputStream inputStream = http.getInputStream();
        int size = inputStream.available();
        byte[] bytes = new byte[size];
        inputStream.read(bytes);
        String message = new String(bytes, "UTF-8");
        System.out.println(message);
        os.flush();//清空输出刘
        os.close();

    } catch (MalformedURLException e) {
        throw new RuntimeException(e);
    } catch (IOException e) {
        throw new RuntimeException(e);
    }

}
}

